package day21;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

/**
 * 
 * StudentUtils.java
 * 
 * @author wangbiao<br/>
 *         email:785497344@qq.com
 * @description
 * @since 1.0.0
 * @date 2013-7-1下午10:43:05
 * 
 */
public class StudentUtils {

	public static Set<Student> getStudentList() {
		return getStudentList(null);
	}

	public static Set<Student> getStudentList(Comparator<Student> cmp) {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String line = null;
		Set<Student> set = null;
		// 如果传入了比较器即按照比较器排序，如果没有即按照默认比较器排序
		if (null == cmp) {
			set = new TreeSet<Student>();
		} else {
			set = new TreeSet<Student>(cmp);
		}
		try {
			while ((line = br.readLine()) != null) {
				// 建议使用org.apache.commons.lang.StringUtils.split(",")
				// 性能更优
				String[] arr = line.split(",");
				if (arr.length < 4) {
					throw new ArrayIndexOutOfBoundsException("数组角标越界！");
				}
				Student student = new Student(arr[0], Integer.parseInt(arr[1]),
						Integer.parseInt(arr[2]), Integer.parseInt(arr[3]));
				set.add(student);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != br) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return set;
	}

	public static void writeToFile(Set<Student> set) {
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new FileWriter("student.txt"));
			for (Student student : set) {
				bw.write(student.toString() + "\t");
				bw.write(student.getSum() + "");
				bw.newLine();
				bw.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != bw) {
				try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
